import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  Select,
  message,
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import './index.scss'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { useEffect, useRef, useState } from 'react'
import { useStore } from '@/store'
import { observer } from 'mobx-react-lite'
import { http } from '@/utils'

const { Option } = Select

function Publish() {
  const [value, setValue] = useState()
  const { channelStore } = useStore()
  const cacheImgList = useRef([])
  const [params] = useSearchParams()
  const id = params.get('id')
  const formRef = useRef()
  const navigate = useNavigate()

  const items = [
    {
      title: '首页',
    },
    {
      title: id ? '编辑文章' : '发布文章',
    },
  ]

  const onFinish = async (values) => {
    const { channel_id, content, title, type } = values
    const params = {
      channel_id,
      content,
      title,
      type,
      cover: {
        type: type,
        images: fileList.map((item) => item.url),
      },
    }

    if (id) {
      const res = await http.put(`/mp/articles/${id}?draft=false`, params)
    }
    const res = await http.post('/mp/articles?draft=false', params)

    navigate('/article')

    message.success(id ? '编辑成功' : '新增成功')
  }

  const [fileList, setFileList] = useState([])

  const onUploadChange = ({ fileList }) => {
    const result = fileList.map((file) => {
      // 上传完毕，做数据处理
      if (file.response) {
        return {
          url: file.response.data.url,
        }
      }
      // 正在上传中，不做处理
      return file
    })
    cacheImgList.current = result
    setFileList(result)
  }

  const [imageCount, setImageCount] = useState(1)

  const onRadioChange = (e) => {
    const rawVal = e.target.value
    setImageCount(e.target.value)
    if (rawVal === 1) {
      const firstImg = cacheImgList.current ? cacheImgList.current[0] : []
      setFileList([firstImg])
    } else if (rawVal === 3) {
      setFileList(cacheImgList.current)
    }
  }

  useEffect(() => {
    const getArticle = async () => {
      const res = await http.get(`/mp/articles/${id}`)
      formRef.current.setFieldsValue({
        ...res,
        type: res.cover.type,
      })

      const formatList = res.cover.images.map((url) => ({ url }))

      setFileList(formatList)

      setImageCount(res.cover.type)

      cacheImgList.current = formatList
    }

    if (id) {
      getArticle()
    }
  }, [id])

  return (
    <div className='publish'>
      <Card title={<Breadcrumb separator='>' items={items} />}>
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 1, content: 'this is content' }}
          onFinish={onFinish}
          ref={formRef}
        >
          <Form.Item
            label='标题'
            name='title'
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder='请输入文章标题' style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label='频道'
            name='channel_id'
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Select placeholder='请选择文章频道' style={{ width: 400 }}>
              {channelStore.channelList.map((item) => (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item label='封面'>
            <Form.Item name='type'>
              <Radio.Group onChange={onRadioChange}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {imageCount > 0 && (
              <Upload
                name='image'
                listType='picture-card'
                className='avatar-uploader'
                showUploadList
                action='http://geek.itheima.net/v1_0/upload'
                fileList={fileList}
                onChange={onUploadChange}
                multiple={imageCount > 1}
                maxCount={imageCount}
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            )}
          </Form.Item>
          <Form.Item
            label='内容'
            name='content'
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            <ReactQuill theme='snow' value={value} onChange={setValue} />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size='large' type='primary' htmlType='submit'>
                {id ? '编辑' : '发布' + '文章'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default observer(Publish)
